package org.je.json;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author fan yi feng
 */
public class JsonArray
{
	private final List<Object>	arr	= new ArrayList<Object>();

	/**
	 * @param obj
	 */
	public void add(Object obj) {
		arr.add(obj);
	}

	/**
	 * 
	 * @param idx
	 * @return
	 */
	public Object remove(int idx) {
		return arr.remove(idx);
	}

	/**
	 * @param obj
	 */
	public void remove(Object obj) {
		Iterator<Object> it = arr.iterator();
		while (it.hasNext()) {
			Object o = it.next();
			if (eq(o, obj)) {
				it.remove();
				break;
			}
		}
	}

	/**
	 * @param idx
	 * @param obj
	 */
	public void set(int idx, Object obj) {
		arr.set(idx, obj);
	}

	/**
	 * 
	 * @return length
	 */
	public int length() {
		return arr.size();
	}

	/**
	 * @param idx
	 * @return Json
	 */
	public Json getJson(int idx) {
		Object res = arr.get(idx);

		return (Json) res;
	}

	/**
	 * @param idx
	 * @return obj
	 */
	public Object get(int idx) {
		return arr.get(idx);
	}

	/**
	 * 
	 */
	public List<Object> getArray() {
		return arr;
	}

	@Override
	public String toString() {
		return getArrayString(this, 0);
	}

	static String getArrayString(JsonArray array, int num) {
		StringBuilder bf = new StringBuilder();
		bf.append(Json.getLevel(num) + "[\r\n");

		int count = 0;

		for (int i = 0; i < array.length(); ++i) {
			Object o = array.get(i);

			if (o instanceof Json) {
				bf.append(Json.getJsonString((Json) o, num + 1));
			} else if (o instanceof JsonArray) {
				bf.append(getArrayString((JsonArray) o, num + 1));
			} else {
				bf.append(Json.getLevel(num + 1) + Json.dealStr(o == null ? null : o.toString()));
			}

			++count;

			if (count != array.length()) {
				bf.append(",");
			}
			bf.append("\r\n");

		}
		bf.append(Json.getLevel(num) + "]");
		return bf.toString();
	}

	private boolean eq(Object o1, Object o2) {
		if (o1 == o2)
			return true;
		if (o1 == null || o2 == null)
			return false;
		return o1.equals(o2);
	}
}
